package javase.jmx.remote;


import java.io.IOException;
import java.net.MalformedURLException;

import javase.jmx.mxbeans.QueueSample;
import javase.jmx.mxbeans.QueueSamplerMXBean;

import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class RemoteMXBeanClient {

	public static void main(String[] args) throws Exception {
		testRemoteAccessToMXBean();
	}

	private static void testRemoteAccessToMXBean() throws MalformedURLException, IOException, MalformedObjectNameException {
        echo("Perform operations on QueueSampler MXBean");
        // service should be launched with parameters -Dcom.sun.management.jmxremote.port=9998 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false
        JMXServiceURL mxbeanUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9998/jmxrmi");
        JMXConnector jmxMXBeanConnector = JMXConnectorFactory.connect(mxbeanUrl, null);
        
        MBeanServerConnection mXBeanServerConnector = jmxMXBeanConnector.getMBeanServerConnection();
        
        ObjectName mxbeanName = new ObjectName("javase.jmx.mxbeans:type=QueueSampler");

        QueueSamplerMXBean mxbeanProxy = JMX.newMXBeanProxy(mXBeanServerConnector, mxbeanName, QueueSamplerMXBean.class);
        
        emtyLine();
        QueueSample queue1 = mxbeanProxy.getQueueSample();
        echo("QueueSample.Date = " + queue1.getDate());
        echo("QueueSample.Head = " + queue1.getHead());
        echo("QueueSample.Size = " + queue1.getSize());

        echo("Invoke clearQueue() in QueueSampler MXBean...");
        mxbeanProxy.clearQueue();

        emtyLine();
        QueueSample queue2 = mxbeanProxy.getQueueSample();
        echo("QueueSample.Date = " + queue2.getDate());
        echo("QueueSample.Head = " + queue2.getHead());
        echo("QueueSample.Size = " + queue2.getSize());


        echo("Close the connection to the server");
        jmxMXBeanConnector.close();
	}


    private static void echo(String msg) {
        System.out.println(msg);
    }
    
    private static void emtyLine() {
		echo("");
	}
}

